package com.b.service.impl;

import com.b.domain.ProductCategory;
import com.b.repository.ProductCategoryRepository;
import com.b.repository.ProductRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import com.b.domain.Product;
import com.b.dao.ProductMapper;
import com.b.service.ProductService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService{

    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductRepository productRepository;
    @Resource
    private ProductCategoryRepository productCategoryRepository;

    @Override
    @Transactional
    public boolean deleteByPrimaryKey(Integer id) {
        try{
            productMapper.deleteByPrimaryKey(id);
            productRepository.deleteById(id);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public int insert(Product record) {
        return productMapper.insert(record);
    }

    @Override
    public int insertSelective(Product record) {
        return productMapper.insertSelective(record);
    }

    @Override
    public Product selectByPrimaryKey(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Product record) {
        return productMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Product record) {
        return productMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Product> getAll() {
        return productMapper.getAll();
    }

    @Override
    public SearchPage<Product> findProductByTitleLikeAndCategoryIdAndDescriptionLike(
            String title, Integer categoryId, String description, PageRequest pageRequest) {

        SearchPage<Product> products;
        if (categoryId != null && categoryId == -1) {
            // 查询所有分类的商品
            products = productRepository.findProductByTitleLikeAndDescriptionLike(title, description, pageRequest);
        } else {
            products = productRepository.findProductByTitleLikeAndCategoryIdAndDescriptionLike(title, categoryId, description, pageRequest);
        }

        // 增加空值检查，避免空指针异常
        if (products != null && products.hasContent()) {
            for (SearchHit<Product> productHit : products) {
                // 1. 获取商品对象（从SearchHit中提取content）
                Product product = productHit.getContent();

                // 2. 获取商品的分类ID（categoryId），而非商品自身的ID
                Integer categoryIdOfProduct = product.getCategoryId();

                // 3. 用分类ID查询分类信息
                if (categoryIdOfProduct != null) {
                    Optional<ProductCategory> categoryOptional = productCategoryRepository.findById(categoryIdOfProduct);

                    // 4. 提取分类名称（如果存在），而非直接拼接Optional对象
                    String categoryName = categoryOptional.map(ProductCategory::getType).orElse("未知分类");

                    // 5. 设置分类名称到商品对象
                    product.setType(categoryName);
                }
            }
        }
        return products;
    }

    @Override
    @Transactional
    public boolean add(Product product) {
        try{
            //先保存到数据库
            productMapper.insert(product);
            //再保存到es
            productRepository.save(product);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    @Transactional
    public boolean update(Product product) {
        try{
            //先保存到数据库
            productMapper.updateByPrimaryKey(product);
            //再保存到es
            productRepository.save(product);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
